<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * @author		PyroCMS Dev Team
 * @package		PyroCMS\Core\Modules\Users\Models
 */
class Luser_m extends MY_Model
{
	public function __construct()
	{
		parent::__construct();
	}


	public function getUser($id)
	{
		$sql="SELECT * from l_user WHERE user_id = ?";

		return $this->db->query($sql, array($id))->row();
	}

	public function getAllUserByType($userType){
		$sql="SELECT l.*, u.username FROM l_user l INNER JOIN default_users u ON u.id = l.user_id WHERE user_type=?";
		return $this->db->query($sql, array($userType))->result();
	}

	public function updateUser($userData){

		$userData=$this->userSettingConstrain($userData);
		$sql="UPDATE l_user SET user_type= ?,agent_id = ?, affiliate_id= ? , commission_rate = ? , agent_rate = ?, affiliate_rate = ?, affiliate_commission_rate = ?";
		$sql.=" WHERE user_id = ?";
		$this->db->query($sql, array(
		$userData->user_type,
		$userData->agent_id,
		$userData->affiliate_id,
		$userData->commission_rate,
		$userData->agent_rate,
		$userData->affiliate_rate,
		$userData->affiliate_commission_rate,
		$userData->user_id
		));
	}

	public function  addUser($userData){
		$userData=$this->userSettingConstrain($userData);

		$sql="INSERT INTO l_user(user_type,agent_id,affiliate_id ,commission_rate,agent_rate,affiliate_rate,affiliate_commission_rate,user_id) "
		."VALUES(?,?,?,?,?,?,?,?)";

		$this->db->query($sql, array(
		$userData->user_type,
		$userData->agent_id,
		$userData->affiliate_id,
		$userData->commission_rate,
		$userData->agent_rate,
		$userData->affiliate_rate,
		$userData->affiliate_commission_rate,
		$userData->user_id
		));
	}

	public function deleteUser($userId){

		$sql="DELETE FROM l_user WHERE user_id = ?";
		$this->db->query($sql, array($userId));
	}

	private function userSettingConstrain($userData){
		if($userData->user_type=="ADMIN"){
			$userData->agent_id=0;
			$userData->affiliate_id=0;
			$userData->commission_rate=0;
			$userData->agent_rate=0;
			$userData->affiliate_rate=0;
			$userData->affiliate_commission_rate=0;
		}
		else if($userData->user_type=="AGENT"){
			$userData->agent_id=0;
			$userData->commission_rate=0;
			$userData->affiliate_id=0;
			$userData->affiliate_rate=0;
			$userData->affiliate_commission_rate=0;
		}
		else if($userData->user_type=="AFFILIATE"){
			$userData->commission_rate=0;
			$userData->agent_id=0;
			$userData->affiliate_id=0;
			$userData->commission_rate=0;
			$userData->agent_rate=0;
		}
		else{
			$userData->agent_rate=0;
			$userData->affiliate_rate=0;
			$userData->affiliate_commission_rate=0;
		}

		return $userData;
	}
}